package com.conding365.gateway.server.filter;

import com.conding365.gateway.server.properties.DoNotVaidateToken;
import com.conding365.gateway.server.rpc.UserFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ValidateFilter implements GlobalFilter,Ordered {

    @Autowired
    private DoNotVaidateToken doNotVaidateToken;

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getPath().value();
        if (!isNeedValidateToken(path)){
            return chain.filter(exchange);
        }

        //验证token是否合法
        Boolean succ = validateToken(request);
        if (!succ){
            //token验证不合法，直接返回401
            System.out.println("token校验不通过！！！");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String data = "token校验不通过!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }

        return chain.filter(exchange);
    }

    private Boolean validateToken(ServerHttpRequest request){
        //先判断是否需要当前调用的接口是否需要验证token
        Boolean needValidateToken = isNeedValidateToken(request.getPath().value());
        if (!needValidateToken){
            return true;
        }
        List<HttpCookie> token = request.getCookies().get("token");
        if(token == null){
            return false;
        }
        HttpCookie httpCookie = token.get(0);
        if (httpCookie == null){
            return false;
        }
        String value = httpCookie.getValue();
        if (StringUtils.isEmpty(value)){
            return false;
        }
        Map<String, ?> stringMap = userFeignClient.checkToken(value);
        if (stringMap != null){
             String user_name = (String) stringMap.get("user_name");
             if (!StringUtils.isEmpty(user_name)){
                 return true;
             }
        }

        return false;
    }

    private Boolean isNeedValidateToken(String path){
        List<String> list = doNotVaidateToken.getList();
        for (String prefix : list){
            if (path.startsWith(prefix)){
                return false;
            }
        }

        return true;
    }


    @Override
    public int getOrder() {
        return 1;
    }
}
